package input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

/**
 * A State that a keyboard can have.
 * Includes a static previous state that can be used to compare states.
 * @author Teem Deer
 */
public class KeyboardState implements KeyListener {

	private static KeyboardState singletonInstance;
	
	private ArrayList<Integer> keysPressed = new ArrayList<Integer>();

	private static KeyboardState previousKeyboardState = new KeyboardState();

	// Constructor and singleton getter
	
	private KeyboardState() {
	}

	/**
	 * 
	 * @return the singleton instance.
	 */
	public static KeyboardState getInstance() {
		if (singletonInstance == null){
			singletonInstance = new KeyboardState();
		}
		return singletonInstance;
	}

	// Updates
	
	/**
	 * Updates the previous KeyboardState.
	 */
	@SuppressWarnings("unchecked")
	public void updatePreviousKeyboardState(){
		previousKeyboardState.keysPressed = (ArrayList<Integer>) this.keysPressed.clone();
	}
	

	@Override
	public void keyPressed(final KeyEvent e) {
		if (!this.keysPressed.contains(e.getKeyCode())) {
			this.keysPressed.add(e.getKeyCode());
		}
	}

	@Override
	public void keyReleased(final KeyEvent e) {
		this.keysPressed.remove((Integer) e.getKeyCode());
	}

	@Override
	public void keyTyped(final KeyEvent e) {
		// not used in our application
	}
	
	/**
	 * 
	 * @param k the keycode
	 * @return true if the key is currently pressed.
	 */
	public boolean isKeyPressed(final int k) {
		return this.keysPressed.contains(k);
	}

	/**
	 * 
	 * @param k the keycode
	 * @return true if the key is currently not pressed.
	 */
	public boolean isKeyUp(final int k) {
		return !this.keysPressed.contains(k);
	}
	
	/**
	 * @return the KeyboardState since last update.
	 */
	public KeyboardState getPreviousKeyboardState(){
		return KeyboardState.previousKeyboardState;
	}

}
